<template>
  <div class="printWrap" v-title="title">
    <div class="containWrap">
      <div class="imgWrap">
        <img width="181" src="./print.png" alt="">
      </div>
      <div class="msg">微信打印文件更方便快捷，赶紧去上传打印文件吧~</div>
      <a href="javascript:;" class="btn upload" @click="chooseImg">上传图片</a>
      <a v-show="isAndroid" href="javascript:;" class="upload btn">上传文件
        <!-- <a v-show="true" href="javascript:;" class="upload btn">上传文件 -->
        <input type="file" id="file" @change="doUpload" />
      </a>

    </div>

  </div>
</template>

<script>
  export default {
    data() {
      return {
        title: "打印",
        id: "upload",
        percentage: 0,
        isAndroid: false,
        uplaodType: "img",
        region: "oss-cn-shenzhen",
        bucket: "ydd-filestore",
        loading: ''
      };
    },
    methods: {
      chooseImg() {
        let that = this;
        // alert('wxchosse')
        console.log("wxchoose");
        wx.chooseImage({
          count: 1, // 默认9
          sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            var localIds = res.localIds.toString(); // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            // 上传图片
            wx.uploadImage({
              localId: localIds, // 需要上传的图片的本地ID，由chooseImage接口获得
              isShowProgressTips: 1, // 默认为1，显示进度提示
              success: function (res) {
                // alert(JSON.stringify(res))
                let MediaId = res.serverId; // 返回图片的服务器端ID
                sessionStorage.setItem('MediaId', MediaId)
                sessionStorage.setItem('fileType', "img")
                sessionStorage.setItem('Extension', 'jpg')
                sessionStorage.setItem('PageCount',1)
                sessionStorage.setItem('fileName', '本地图片')
                // 下载图
                that.goToPinter(MediaId);
              }
            });
          }
        });
      },
      goToPinter(MediaId) {

        axios
          .post(`/job/Upload?mediaId=${MediaId}`)
          .then(res => {
            sessionStorage.setItem('pageCount', 1)
            sessionStorage.setItem("fromWay", "upload")
            this.$router.push("/setting");
          })
          .catch(err => {
            console.log(err);
            weui.topTips("上传失败");
          });
      },
      getConfig() {
        let url = `${this.$url}/job/GetJsApiParam?url=${this.$url}/index.html`;
        this.$axios
          .get(url)
          .then(res => {
            console.log(res);
            wx.config({
              // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: res.data.Data.AppId, // 必填，企业号的唯一标识，此处填写企业号corpid
              timestamp: res.data.Data.TimeStamp, // 必填，生成签名的时间戳
              nonceStr: res.data.Data.NonceStr, // 必填，生成签名的随机串
              signature: res.data.Data.Signature, // 必填，签名，见附录1
              jsApiList: ["chooseImage", "uploadImage"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function () {
              console.log("ready");
            });
            wx.error(function () {
              console.log("errr");
              // weui.alert("配置信息错");
            });
          })
          .catch(err => {
            // weui.alert("配置信息错");
          });
      },
      doUpload() {
        this.loading = weui.loading('loading', {
          className: 'custom-classname'
        });
        axios
          .post("/Account/GetOssAccessToken")
          .then(res => {
            console.log(res);
            let client = new OSS.Wrapper({
              region: this.region,
              endpoint: "https://oss-cn-shenzhen.aliyuncs.com",
              accessKeyId: res.data.Data.AccessKeyId,
              accessKeySecret: res.data.Data.AccessKeySecret,
              stsToken: res.data.Data.SecurityToken,
              bucket: this.bucket
            });
            let file = document.getElementById("file").files[0];
            let raname =
              this.random_string(6) +
              new Date().getTime() +
              "." +
              file.name.split(".").pop();
            console.log(raname);
            client
              .multipartUpload(raname, file)
              .then(results => {
                let MediaId = results.name;
                let typeArr = results.name.split(".") || [];
                let Extension = typeArr[typeArr.length - 1];
                sessionStorage.setItem('Extension', Extension)
                sessionStorage.setItem("fileType", "file");
                sessionStorage.setItem("MediaId", MediaId)
                sessionStorage.setItem('fileName', file.name)
                //获取打文档页数
                // alert('准备进入获取页数方法')
                axios.get(`/user/getfilepagecount?aliyunFileName=${results.name}`)
                  .then(res => {
                    if (res.data.IsSuccess) {
                      this.loading.hide()
                      let PageCount = res.data.Data || 1
                      sessionStorage.setItem('PageCount', PageCount)
                      sessionStorage.setItem("fromWay", "upload")
                      this.$router.push("/setting");
                    } else {
                      this.loading.hide()
                      weui.alert(res.data.Msg)
                    }
                  })
                  .catch(err => {
                    this.loading.hide()
                  })

              })
              .catch(err => {
                console.log(err);
                this.loading.hide()
              });
          })
          .catch(err => {
            console.log("err");
            this.loading.hide()
          });
      },
      random_string(len) {
        len = len || 32;
        var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
        var maxPos = chars.length;
        var pwd = "";
        for (let i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
      },
      checkPlatform() {
        var u = navigator.userAgent;
        console.log(u);
        this.isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      }
    },
    created() {
      this.checkPlatform();
      this.getConfig();
    },
    beforeDestroy() {
      if (loading) {
        this.loading.hide()
      }
    }

  };

</script>

<style lang='less' scoped>
  .printWrap {
    text-align: center;
    .containWrap {
      width: 181px;
      display: inline-block;
      margin: 2.4rem auto 0;
      .imgWrap {
        height: 181px;
      }
      .msg {
        padding-top: 15px;
        text-align: left;
        color: #3d4244;
        font-size: 15px;
        margin-bottom: 2.533333rem;
      }
      .upload {
        width: 181px;
        height: 42px;
        color: #fff;
        background: #19a4ff;
        font-size: 16px;
        line-height: 42px;
        text-decoration: none;
        position: relative;
        margin-bottom: 10px;
        input {
          position: absolute;
          right: 0;
          top: 0;
          left: 0;
          bottom: 0;
          opacity: 0;
          filter: alpha(opacity=0);
        }
      }
    }
  }

</style>
